import { promises as fs } from "fs";
import { IconSet, exportToDirectory } from "@iconify/tools";
import { validateIconSet, getIconData, iconToSVG, iconToHTML, replaceIDs } from "@iconify/utils";
import { icons as iconsEp } from "@iconify-json/ep";
import { icons as iconsMdi } from "@iconify-json/mdi";

type IconType = "ep" | "mdi";

async function fetchIcon(iconsArray: string[], iconType: IconType) {
  try {
    const res = {
      prefix: iconType,
      icons: {},
    };
    let icons = iconType === "ep" ? iconsEp : iconsMdi;
    iconsArray.forEach(async (iconName) => {
      const data = await getIconData(icons, iconName);
      if (data) {
        res.icons[iconName] = data;
      } else {
        console.error(`${iconName} is notfound in ${iconType}`);
      }
    });
    return res;
  } catch (error) {
    console.error(`fetch icon error`, error);
  }
}

async function generateIconsJson(iconsArray: string[], iconType: IconType) {
  let jsonPath = iconType === "ep" ? "./src/json/icons.json" : "./src/json/iconsMdi.json";
  const rawData = await fetchIcon(iconsArray, iconType);
  await fs.writeFile(jsonPath, JSON.stringify(rawData));
}

(async () => {
  // @iconify-json/ep
  const iconsEp = [
    "setting",
    "unlock",
    "d-arrow-right",
    "d-arrow-left",
    "refresh-right",
    "menu",
    "full-screen",
    "close",
    "delete",
  ];
  const iconsMdi = [
    "shield-lock-outline",
    "logout",
    "menu",
    "translate",
    "close-fullscreen",
    "add",
    "file-export",
    "file-import",
  ];
  // await generateIconsJson(iconsEp, "ep");
  // await generateIconsJson(iconsMdi, "mdi");
  await Promise.all([generateIconsJson(iconsEp, "ep"), generateIconsJson(iconsMdi, "mdi")]);

  // 导出svg图标到文件夹
  // const iconSet = new IconSet(rawData!);
  // await exportToDirectory(iconSet, {
  // target: "iconify-output",
  // });
})();
